﻿using System;
using System.Collections.Generic;
using System.Linq;
using Sustainalytics.DataLayer;
using Sustainalytics.DataLayer.Shared;
using Sustainalytics.Entities.Governance;


namespace Sustainalytics.Governance.Synchronization
{
    public class GovernancePdfFilesReader
    {
        private IRepositoryCollection<GovernancePdfProfileMetadata> _repository;
        private IFileRepository _fileRepository;

        private GovernancePdfFilesReader() { }

        public static GovernancePdfFilesReader GetInstance(string connectionString)
        {
            if (string.IsNullOrEmpty(connectionString))
                throw new ArgumentException("A connection string must be provided to create an IClientPlatformDataReader instance!");

            return new GovernancePdfFilesReader
            {
                _repository = new RepositoryCollection<GovernancePdfProfileMetadata>(connectionString),
                _fileRepository = new FileRepository(connectionString)
            };
        }

        public List<GovernancePdfProfileMetadata> GetChangedPdfFiles(DateTime changedSince)
        {
            return _repository.ReadWhere(x => x.LastOperationDateTime >= changedSince.Date).ToList();
        }

        public byte[] GetPdfFile(Guid fileId, GovernancePdfType pdfType)
        {
            var result = _fileRepository.GetDownloadStream(fileId);


            if (result.Item1 == null) return null;

            var pdfFile = new byte[result.Item1.Length];
           
            result.Item1.Read(pdfFile, 0, (int)result.Item1.Length);

            return pdfFile;
        }
    }
}
